<script setup lang="ts">
  import { addPatientAPI, editPatientAPI, getPatientDetailAPI } from '@/api/patients'
  import type { PatientItem } from '@/types/patient'
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'
  //在编辑患者页面获取患者数据
  const id = ref('')
  onLoad(async (params) => {
    if (!params?.id) return
    id.value = params.id
    uni.setNavigationBarTitle({ title: '编辑患者' })
    //获取患者数据
    formData.value = await getPatientDetailAPI(params.id)
  })
  //表单数据
  const formData = ref<PatientItem>({
    name: '',
    idCard: '360733200205283619',
    gender: 0,
    defaultFlag: 0,
  })
  //定义同名ref对象
  const formRef = ref<UniHelper.UniFormsInstance>()
  //表单验证规则
  const rules: UniHelper.UniFormsRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请输入患者姓名' },
        { pattern: /^[\u4e00-\u9fa5]{2,5}$/, errorMessage: '请输入正确的姓名' },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请输入身份证号' },
        {
          pattern:
            /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}[\dXx]$/,
          errorMessage: '请输入正确的身份证号',
        },
      ],
    },
    gender: {
      rules: [
        {
          validateFunction: (rule, value, data, callback) => {
            const sexNum = Number(formData.value.idCard!.charAt(16))
            const isOk = sexNum % 2 === value % 2
            return isOk || callback('请选择正确的性别')
          },
        },
      ],
    },
  }
  //保存患者数据
  const onSave = async () => {
    await formRef.value?.validate!()

    if (id.value) {
      console.log('formData.value --->', formData.value)
      await editPatientAPI({
        name: formData.value.name,
        id: id.value,
        gender: formData.value.gender,
        defaultFlag: formData.value.defaultFlag,
        idCard: formData.value.idCard,
      })
      uni.showToast({ title: '更新成功', icon: 'success' })
      uni.navigateBack()
      return
    }
    await addPatientAPI(formData.value)
    uni.navigateBack()
    uni.showToast({
      title: '保存成功',
      icon: 'none',
      duration: 1500,
    })
  }
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms :model="formData" :rules="rules" border label-width="220rpx" ref="formRef">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :style="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :style="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            mode="tag"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人">
          <view class="uni-switch">
            <switch
              :checked="!!formData.defaultFlag"
              @change="formData.defaultFlag = $event.detail.value ? 1 : 0"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSave">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './form.scss';
</style>
